import os
from xml.dom.minidom import parse

class Module:
    def __init__(self, dir, name):
        self._name = name
        self._dir = dir + "/modules/mod_" + self._name

    def add_file(self, filename):
        fh = open(self._dir + "/" +filename, "w")

        dom = parse(self._dir + "/mod_" + self._name + ".xml")
        filesNode = dom.getElementsByTagName("files")[0]
        filenameNode = dom.createElement("filename")

        filenameNode.appendChild(dom.createTextNode(filename))
        filesNode.appendChild(filenameNode)

        fh = open(self._dir + "/mod_" + self._name + ".xml", "w")
        dom.writexml(fh, encoding="UTF-8")

    def create(self):
        name = raw_input('name:')
        desc = raw_input("description:")

        os.mkdir(self._dir)
        fh = open(self._dir + "/mod_" + self._name + ".php", "w")
        fh.write("<?php\n defined('_JEXEC') or die('Restricted access');\n"+
        " require_once(dirname(__FILE__).DS.'helper.php');\n require(JModuleHelper::getLayoutPath('mod_" + self._name + "'));\n?>")

        fh = open(self._dir + "/helper.php", "w")
        fh.write("<?\n defined('_JEXEC') or die('Restricted access');\n?>")

        fh = open(self._dir + "/index.html", "w")
        fh.write("<html><body bgcolor=\"#FFFFFF\"></body></html>")

        fh = open(self._dir + "/mod_" + self._name + ".xml", "w")
        fh.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<install type=\"module\" version=\"1.5.0\">\n" +
        "<name>" + name +"</name>\n<author>Cytrus Tech</author>\n<version>1.5.0</version>\n" +
        "<description>" + desc + "</description>\n" +
        "<files>\n<filename>mod_" + self._name +".xml</filename>\n<filename module=\"mod_" + self._name + "\">mod_" + self._name + ".php</filename>\n" +
        "<filename>index.html</filename>\n<filename>helper.php</filename>\n<filename>tmpl/default.php</filename>\n" +
        "<filename>tmpl/index.html</filename>\n</files>\n<params>\n</params></install>")

        #create template files
        os.mkdir(self._dir + "/tmpl")

        fh = open(self._dir + "/tmpl/index.html", "w")
        fh.write("<html><body bgcolor=\"#FFFFFF\"></body></html>")

        fh = open(self._dir + "/tmpl/default.php", "w")
        fh.write("<?\n defined('_JEXEC') or die('Restricted access');\n?>")        